import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { DeepPartial, FindManyOptions, FindOneOptions, Repository } from 'typeorm';
import { User } from './entities/user.entity';
import * as bcrypt from 'bcrypt';
import { workerId } from '../data_base_config/config'
import {AuthService} from'src/auth/auth.services'
import {httpException} from 'src/filter/httpException/httpException'
import { Redis_db0 } from'src/redis/redis.config'
const snowId = require('simple-flakeid');
@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
    private authService: AuthService
  ) {}
  
  findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }

  async remove(id: string): Promise<void> {
    await this.usersRepository.delete(id);
  }

  async findOne(user: DeepPartial<User>):Promise<User[]>{
    const option = {
      where:{
        userName:user.userName
      }
    } as FindManyOptions
    return this.usersRepository.find(option);
  }

  async register(user: DeepPartial<User>){    
    const result = await this.findOne(user)
    if(result.length > 0){
      httpException('用户名重复');
    }
    const genId = new snowId.SnowflakeIdv1({ workerId: workerId});
    const saltOrRounds = 10;
    user.id = genId.NextId();
    user.password = await bcrypt.hash(user.password, saltOrRounds);
    const saveUser = await this.usersRepository.save(user);
    if(saveUser){
      return saveUser;
    } 
  }
  
  async login(user:DeepPartial<User>): Promise<any> { 
    const result = await this.findOne(user) 
    try{ 
      let isMatch = false;
      if(result.length > 0) {
        isMatch = await bcrypt.compare(user.password,result[0].password);
      }
      if(isMatch){
        const payload = { id: result[0].id};
        //redis测试写数据
        const Redisresulet = await Redis_db0.set(result[0].id, JSON.stringify(payload), "EX", 10*60)
        if(Redisresulet !=='ok'){
          httpException('系统出错，请重试');
        }
        return this.authService.tokenAuth(payload);
      }else{
        httpException('用户名或密码错误');
      }
    }catch{
      httpException('系统出错');
    }  
  }
}
